package com.lufei.message_system.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lufei.message_system.Data.PageResult;
import com.lufei.message_system.Data.Result;
import com.lufei.message_system.Data.TestResult;
import com.lufei.message_system.Data.TestResultVD.*;
import com.lufei.message_system.Mapper.TestResultMapper;
import com.lufei.message_system.Service.TestResultService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TestResultServiceImpl implements TestResultService {
    @Autowired
    private TestResultMapper testResultMapper;

    @Override
    public Result<TestResultVO> createTestResult(TestResultCreateDTO createDTO) {
        // 检查学号是否为空
        if (!StringUtils.hasText(createDTO.getUserId())) {
            return Result.error("学号不能为空");
        }

        // 检查该用户是否已经有测试结果
        QueryWrapper<TestResult> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", createDTO.getUserId());
        List<TestResult> existingResults = testResultMapper.selectList(queryWrapper);

        // DTO转Entity
        TestResult testResult = new TestResult();
        BeanUtils.copyProperties(createDTO, testResult);
        
        // 设置当前服务器时间
        testResult.setTestTime(new Date());

        // 确保分数不为null
        testResult.setEScore(testResult.getEScore() != null ? testResult.getEScore() : 0);
        testResult.setIScore(testResult.getIScore() != null ? testResult.getIScore() : 0);
        testResult.setSScore(testResult.getSScore() != null ? testResult.getSScore() : 0);
        testResult.setNScore(testResult.getNScore() != null ? testResult.getNScore() : 0);
        testResult.setTScore(testResult.getTScore() != null ? testResult.getTScore() : 0);
        testResult.setFScore(testResult.getFScore() != null ? testResult.getFScore() : 0);
        testResult.setJScore(testResult.getJScore() != null ? testResult.getJScore() : 0);
        testResult.setPScore(testResult.getPScore() != null ? testResult.getPScore() : 0);

        // 计算MBTI类型
        String mbtiType = calculateMbtiType(
            testResult.getEScore(), testResult.getIScore(),
            testResult.getSScore(), testResult.getNScore(),
            testResult.getTScore(), testResult.getFScore(),
            testResult.getJScore(), testResult.getPScore()
        );
        testResult.setMbtiType(mbtiType);

        // 设置类型名称
        testResult.setTypeName(getMbtiTypeName(mbtiType));

        // 保存到数据库
        int result = testResultMapper.insert(testResult);
        if (result <= 0) {
            return Result.error("创建测试结果失败");
        }

        // 返回结果
        TestResultVO testResultVO = convertToVO(testResult);
        return Result.success(testResultVO);
    }

    // 计算MBTI类型
    private String calculateMbtiType(
            Integer eScore, Integer iScore,
            Integer sScore, Integer nScore,
            Integer tScore, Integer fScore,
            Integer jScore, Integer pScore) {
        
        // 处理可能的null值
        eScore = eScore != null ? eScore : 0;
        iScore = iScore != null ? iScore : 0;
        sScore = sScore != null ? sScore : 0;
        nScore = nScore != null ? nScore : 0;
        tScore = tScore != null ? tScore : 0;
        fScore = fScore != null ? fScore : 0;
        jScore = jScore != null ? jScore : 0;
        pScore = pScore != null ? pScore : 0;
        
        StringBuilder mbtiType = new StringBuilder();
        
        // E-I维度
        if (eScore.equals(iScore)) {
            // 平局情况下默认为I
            mbtiType.append("I");
        } else {
            mbtiType.append(eScore > iScore ? "E" : "I");
        }
        
        // S-N维度
        if (sScore.equals(nScore)) {
            // 平局情况下默认为N
            mbtiType.append("N");
        } else {
            mbtiType.append(sScore > nScore ? "S" : "N");
        }
        
        // T-F维度
        if (tScore.equals(fScore)) {
            // 平局情况下默认为F
            mbtiType.append("F");
        } else {
            mbtiType.append(tScore > fScore ? "T" : "F");
        }
        
        // J-P维度
        if (jScore.equals(pScore)) {
            // 平局情况下默认为P
            mbtiType.append("P");
        } else {
            mbtiType.append(jScore > pScore ? "J" : "P");
        }
        
        System.out.println("计算得到的MBTI类型: " + mbtiType.toString() + 
                          ", 分数: E=" + eScore + ", I=" + iScore + 
                          ", S=" + sScore + ", N=" + nScore + 
                          ", T=" + tScore + ", F=" + fScore + 
                          ", J=" + jScore + ", P=" + pScore);
        
        return mbtiType.toString();
    }

    // 获取MBTI类型名称
    private String getMbtiTypeName(String mbtiType) {
        switch (mbtiType) {
            case "ISTJ": return "检查者";
            case "ISFJ": return "保护者";
            case "INFJ": return "咨询师";
            case "INTJ": return "建筑师";
            case "ISTP": return "鉴赏家";
            case "ISFP": return "探险家";
            case "INFP": return "调停者";
            case "INTP": return "逻辑学家";
            case "ESTP": return "企业家";
            case "ESFP": return "表演者";
            case "ENFP": return "竞选者";
            case "ENTP": return "辩论家";
            case "ESTJ": return "总经理";
            case "ESFJ": return "执政官";
            case "ENFJ": return "主人公";
            case "ENTJ": return "指挥官";
            default: return "未知类型";
        }
    }

    @Override
    public Result<TestResultVO> getTestResultById(Long id) {
        TestResult testResult = testResultMapper.selectById(id);
        if (testResult == null) {
            return Result.error("测试结果不存在");
        }

        TestResultVO testResultVO = convertToVO(testResult);
        return Result.success(testResultVO);
    }

    @Override
    public Result<TestResultVO> updateTestResultById(TestResultUpdateDTO updateDTO) {
        // 检查测试结果是否存在
        TestResult existingResult = testResultMapper.selectById(updateDTO.getId());
        if (existingResult == null) {
            return Result.error("测试结果不存在");
        }

        // 只更新传入的字段，保留其他字段不变
        if (updateDTO.getEScore() != null) {
            existingResult.setEScore(updateDTO.getEScore());
        }
        if (updateDTO.getIScore() != null) {
            existingResult.setIScore(updateDTO.getIScore());
        }
        if (updateDTO.getSScore() != null) {
            existingResult.setSScore(updateDTO.getSScore());
        }
        if (updateDTO.getNScore() != null) {
            existingResult.setNScore(updateDTO.getNScore());
        }
        if (updateDTO.getTScore() != null) {
            existingResult.setTScore(updateDTO.getTScore());
        }
        if (updateDTO.getFScore() != null) {
            existingResult.setFScore(updateDTO.getFScore());
        }
        if (updateDTO.getJScore() != null) {
            existingResult.setJScore(updateDTO.getJScore());
        }
        if (updateDTO.getPScore() != null) {
            existingResult.setPScore(updateDTO.getPScore());
        }

        // 重新计算MBTI类型
        String mbtiType = calculateMbtiType(
            existingResult.getEScore(), existingResult.getIScore(),
            existingResult.getSScore(), existingResult.getNScore(),
            existingResult.getTScore(), existingResult.getFScore(),
            existingResult.getJScore(), existingResult.getPScore()
        );
        existingResult.setMbtiType(mbtiType);
        existingResult.setTypeName(getMbtiTypeName(mbtiType));

        int result = testResultMapper.updateById(existingResult);
        if (result <= 0) {
            return Result.error("更新测试结果失败");
        }

        // 重新查询获取完整数据
        TestResult updatedResult = testResultMapper.selectById(updateDTO.getId());
        TestResultVO testResultVO = convertToVO(updatedResult);
        return Result.success(testResultVO);
    }

    @Override
    public Result<Boolean> deleteTestResultById(Long id) {
        int result = testResultMapper.deleteById(id);
        if (result <= 0) {
            return Result.error("删除测试结果失败");
        }
        return Result.success(true);
    }

    @Override
    public Result<List<TestResultVO>> getTestResultsByUserId(String userId) {
        if (!StringUtils.hasText(userId)) {
            return Result.error("学号不能为空");
        }

        QueryWrapper<TestResult> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .orderByDesc("test_time");

        List<TestResult> testResults = testResultMapper.selectList(queryWrapper);
        List<TestResultVO> vos = testResults.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        return Result.success(vos);
    }

    @Override
    public Result<Boolean> deleteTestResultsByUserId(String userId) {
        if (!StringUtils.hasText(userId)) {
            return Result.error("学号不能为空");
        }

        QueryWrapper<TestResult> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);

        int deleted = testResultMapper.delete(queryWrapper);
        if (deleted <= 0) {
            return Result.error("删除测试结果失败");
        }
        return Result.success(true);
    }

    @Override
    public Result<List<TestResultVO>> updateTestResultsByUserId(String userId, TestResultUpdateDTO updateDTO) {
        if (!StringUtils.hasText(userId)) {
            return Result.error("学号不能为空");
        }

        TestResult updateEntity = new TestResult();
        BeanUtils.copyProperties(updateDTO, updateEntity);

        QueryWrapper<TestResult> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);

        int updated = testResultMapper.update(updateEntity, queryWrapper);
        if (updated <= 0) {
            return Result.error("更新测试结果失败");
        }

        return getTestResultsByUserId(userId);
    }

    @Override
    public PageResult<TestResultVO> queryTestResults(TestResultQueryDTO queryDTO) {
        QueryWrapper<TestResult> queryWrapper = new QueryWrapper<>();

        if (StringUtils.hasText(queryDTO.getUserId())) {
            queryWrapper.eq("user_id", queryDTO.getUserId());
        }
        if (StringUtils.hasText(queryDTO.getMbtiType())) {
            queryWrapper.eq("mbti_type", queryDTO.getMbtiType());
        }

        // 分页查询
        IPage<TestResult> page = new Page<>(queryDTO.getPage(), queryDTO.getSize());
        IPage<TestResult> resultPage = testResultMapper.selectPage(page, queryWrapper);

        // 转换为VO
        List<TestResultVO> vos = resultPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        PageResult<TestResultVO> pageResult = new PageResult<>();
        pageResult.setList(vos);
        pageResult.setTotal(resultPage.getTotal());
        pageResult.setPage((int) resultPage.getCurrent());
        pageResult.setSize((int) resultPage.getSize());

        return pageResult;
    }

    private TestResultVO convertToVO(TestResult testResult) {
        TestResultVO vo = new TestResultVO();
        BeanUtils.copyProperties(testResult, vo);
        return vo;
    }
}